<?php
namespace Common\Model;
use Think\Model;
use Think\Upload;

/**
 * 会员模型
 * insert,update 直接create操作数据即可
 */
class MemberModel extends Model {
	public static $mystat = array('del'=>'-1','forbid'=>'0','allow'=>'1');
	public static $ablemap = array('status'=>'1'); //状态正常的查询条件
	
	
	/**
	 * MUST_VALIDATE	1	必须验证 不管表单是否有设置该字段
	 * VALUE_VALIDATE	2	值不为空的时候才验证
	 * EXISTS_VALIDATE	0	表单存在该字段就验证   (默认)
	 * 
	 * self::MODEL_INSERT或者1	新增数据时候验证
	 * self::MODEL_UPDATE或者2	编辑数据时候验证
	 * self::MODEL_BOTH或者3		全部情况下验证（默认）
	 */
	protected $_validate = array(
			//  \w等价于[A-Za-z0-9_]
			array('mobile','/^1\d{10}$/','请输入正确的手机号码',self::MUST_VALIDATE,'regex',self::MODEL_INSERT),
			array('account','require','会员帐号不能为空',self::MUST_VALIDATE,'regex',self::MODEL_INSERT),
			array('account','','会员已经存在',self::MUST_VALIDATE,'unique',self::MODEL_INSERT),
			array('account','/^\w{4,16}$/i','会员帐号格式错误，字母或数字 4-16位'),//  \w等价于[A-Za-z0-9_]
			
			array('password','require','登录密码必须',self::MUST_VALIDATE,'regex',self::MODEL_INSERT),
			array('repassword','require','确认登录密码必须',self::MUST_VALIDATE,'regex',self::MODEL_INSERT),
			array('repassword','password','登录确认密码不一致',self::MUST_VALIDATE,'confirm',self::MODEL_INSERT),
			
			array('password','require','登录密码必须',self::EXISTS_VALIDATE,'regex',self::MODEL_UPDATE),
			array('repassword','require','确认登录密码必须',self::EXISTS_VALIDATE,'regex',self::MODEL_UPDATE),
			array('repassword','password','登录确认密码不一致',self::EXISTS_VALIDATE,'confirm',self::MODEL_UPDATE),

			array('email','email','请输入正确的邮箱地址',self::EXISTS_VALIDATE,'regex',self::MODEL_BOTH),
			
			array('last_login','number','上次登录时间格式非法'),
			array('logins','number','登录次数格式非法'),
			
			array('status', array('-1','0','1') ,'会员状态非法',self::EXISTS_VALIDATE,'in'),//-1-删除 0-禁用 1-正常
	);
	protected $_auto = array(
			array('reg_time','time',self::MODEL_INSERT,'function'),//注册时间
	);
	
	/**
	 * 查找 状态正常 的属性
	 * @param PKID或者array $options
	 * @return array
	 */
	public function findAble($options=array()) {
		$where = array();
		if (is_numeric($options) || is_string($options)) {
			$where[$this->getPk()]  =   $options;
		}else {
			$where = $options;
		}
	
		if ($where['status']===null||$where['status']===''||!in_array($where['status'],self::$mystat)) $where['status'] = '1';
		return $this->where($where)->find();
	}
	
	/**
	 * 会员自主更新, 先create后调用
	 * @param postArray $data
	 * @return boolean
	 */
	public function myUpdate($data) {
		$id = $data['id']; $orgpwd = $data['orgpwd'];
		unset($data['id']); unset($data['orgpwd']);
		
		if (preg_match('/\S+/',$orgpwd)) {
			//有原始密码, 判断密码是否正确
			$info = $this->where('`id`='.$id)->find();
			if (empty($info)) {
				$this->error = '用户不存在';
				return false;
			}
			if ($info['password'] != pwd_hash($orgpwd)) {
				$this->error = '原始密码不正确';
				return false;
			}
		}else {
			//没有原始密码, 不更新密码
			unset($data['password']);
			unset($data['repassword']);
		}
		//create验证数据
		if (false ===$this->create($data,self::MODEL_UPDATE)) return false;
		
		return $this->where('`id`='.$id)->save();
	}
	
	/**
	 * 登录用户
	 * @param  array $map 用户查询条件 account & password
	 * @return boolean      ture-登录成功，false-登录失败
	 */
	public function login($map) {
		if (empty($map)) {
			$this->error = '登录条件异常！';
			return false;
		}
		$password = $map['password'];
		unset($map['password']);
		
		$logscontent = $map['logscontent'];
		unset($map['logscontent']);
		
		$member = $this->where($map)->find();
		if(!$member || -1 == $member['status']) {
			$this->error = '用户不存在或已被禁用！';
			return false;
		}
		if($member['password'] != pwd_hash($password)) {
			$this->error = '密码错误！';
			return false;
		}
		
		/**登录日志**************************************/
		$memlogs_M = new Model('MemberLogs');
		$logsdata=array(
				'mem_id'=> $member['id'],
				'cate' => '1', //1-登录
				'logstime' => NOW_TIME,
				'content' => $logscontent
		);
		$memlogs_M->add($logsdata);
		/******************************************/
		
		/* 登录用户 */
		$this->_myLogin($member);
	
		// XXX 行为  用户登录
		//tag('member_login');
	
		return true;
	}
	
	public function myReg($data) {
// 		if (false===$this->create($data)) return false;
		$newid = $this->add($data);
		if ($newid<=0) return false;
		$info = $this->find($newid);
		$this->_myLogin($info);
		return true;
	}
	
	public function logout(){
		session('user_auth', null);
		session('user_auth_sign', null);
	}
	
	/**
	 * 自动登录用户
	 * @param  integer $member 用户信息数组
	 */
	private function _myLogin($member){
		/* 更新登录信息 */
		$data = array(
				'id'         => $member['id'],
				'logins'     => array('exp', '`logins`+1'),
				'last_login' => NOW_TIME,
				'last_ip'    => get_client_ip(1)
		);
		$this->save($data);
	
		/* 记录登录SESSION和COOKIES */
		$auth = array(
			'id'		=> $member['id'],
			'account'	=> $member['account'],
			'logins'	=> $member['logins'],
			'last_ip'	=> $member['last_ip'],
			'cate'		=> $member['cate'],
			'mobile'		=> $member['mobile']
		);
		
		session('user_auth', $auth);
		session('user_auth_sign', data_auth_sign($auth));
	}
	
	public function chgPwd($org,$new,$mid){
		$mem = $this->find($mid);
		if($mem['password'] != pwd_hash($org)) {
			$this->error = '原始密码错误！';
			return false;
		}
		return $this->where('id='.$mid)->setField('password',pwd_hash($new));
	}
	/**
	 * 认证
	 */
	public function myRenzheng($data) {
		//先create验证数据
		if (false ===$this->create($data,self::MODEL_UPDATE)) return false;
		
		//身份证正面
		if (!empty($data['zhengmian'])) {
			$setting = C('PICTURE_UPLOAD');
			$Upload = new Upload($setting);
			$image = $Upload->uploadOne($data['zhengmian']);
			if (!$image) {
				$this->error = $Upload->getError();
				return false;
			}
			$image['path'] = $setting['rootPath'].$image['savepath'].$image['savename']; //在模板里的url路径
			$this->zhengmian = $image['path'];
		}else {
			unset($this->zhengmian);
		}//身份证背面
		if (!empty($data['beimian'])) {
			$setting = C('PICTURE_UPLOAD');
			$Upload = new Upload($setting);
			$image = $Upload->uploadOne($data['beimian']);
			if (!$image) {
				$this->error = $Upload->getError();
				return false;
			}
			$image['path'] = $setting['rootPath'].$image['savepath'].$image['savename']; //在模板里的url路径
			$this->beimian = $image['path'];
		}else {
			unset($this->beimian);
		}
	
		return $this->where('`id`='.$data['id'])->save();
	}
}
